package com.tokenmaster.aitrade.trade.kdj;

import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;

import com.tokenmaster.aitrade.common.system.KLinePoint;
import com.tokenmaster.aitrade.data.SystemDB;
import com.tokenmaster.aitrade.trade.ITradeRequest;

/**
 * @Description: KDJ(9,3,3)
 * @author buxinyun
 */
public class Index_KDJ {

	/**
	 * KDJ分析
	 * 
	 * @param Klines
	 */

	private SystemDB systemDB = SystemDB.getInstance();

	private List<KLinePoint> kLinePoints = new ArrayList<KLinePoint>();

	/**
	 * 计算某个点的KDJ
	 * 
	 * @param kLinePoint
	 */
	public Index_KDJ_Info calculation(KLinePoint kLinePoint) {

		// 从数据库读取历史K线
		kLinePoints.clear();
		kLinePoints = systemDB.getKLinePointsBefore(kLinePoint.getSymbol(), kLinePoint.getType(),
				kLinePoint.getUnixTime(), 9);
		

		// 新建KDJ点
		Index_KDJ_Info index_KDJ_Info = new Index_KDJ_Info();
		index_KDJ_Info.setSymbol(kLinePoint.getSymbol());
		index_KDJ_Info.setType(kLinePoint.getType());
		index_KDJ_Info.setUnixtime(kLinePoint.getUnixTime());

		// 获取上一个KDJ点
		Index_KDJ_Info last_Kdj_Info = systemDB.getLastIndexKDJ(kLinePoint.getSymbol(), kLinePoint.getType(),
				kLinePoint.getUnixTime());

		double lastKDJ_KValue = 0;
		double lastKDJ_DValue = 0;

		if (last_Kdj_Info == null) {
			lastKDJ_KValue = 50;
			lastKDJ_DValue = 50;
		} else {
			lastKDJ_KValue = last_Kdj_Info.getkValue();
			lastKDJ_DValue = last_Kdj_Info.getdValue();
		}

		// 计算rsv
		double rsv = calculateRSV(kLinePoints);
		// 计算K值
		double k = (rsv + lastKDJ_KValue * 2) / 3;
		// 计算D值
		double d = (lastKDJ_DValue * 2 + k) / 3;
		// 计算J值
		double j = 3 * k - 2 * d;

		index_KDJ_Info.setRsv(rsv);
		index_KDJ_Info.setkValue(k);
		index_KDJ_Info.setdValue(d);
		index_KDJ_Info.setjValue(j);

		return index_KDJ_Info;

	}

	private double calculateRSV(List<KLinePoint> kLinePoints) {
		int size = kLinePoints.size();
		KLinePoint todayK = kLinePoints.get(size - 1);
		double maxPrice = todayK.getHigh();
		double minPrice = todayK.getLow();

		for (KLinePoint kLinePoint : kLinePoints) {

			if (kLinePoint.getHigh() > maxPrice) {
				maxPrice = kLinePoint.getHigh();
			}
			if (kLinePoint.getLow() < minPrice) {
				minPrice = kLinePoint.getLow();
			}
		}

		if (maxPrice == minPrice) {
			return 100;
		}

		return (todayK.getLast() - minPrice) / (maxPrice - minPrice) * 100;
	}

}
